﻿using System;
using System.Collections.Generic;

namespace MingYuanYun.Configuration
{
    public static class HostingEnvironment
    {
        public const string DefaultEnvironmentName = "ASPNETCORE_ENVIRONMENT";

        private static string _currentEnvironment;

        private static CommandLineParser _commandLineParser;

        public static string GetEnvironment(string environmentName = DefaultEnvironmentName)
        {
            if (!string.IsNullOrEmpty(_currentEnvironment))
                return _currentEnvironment;

            if (_commandLineParser != null)
            {
                _currentEnvironment = _commandLineParser.GetCommandLineVariable(environmentName);
            }

            if (string.IsNullOrEmpty(_currentEnvironment))
            {
                _currentEnvironment = Environment.GetEnvironmentVariable(environmentName);
            }

            return _currentEnvironment;
        }

        public static string GetCommandLineVariable(IEnumerable<string> args, string environmentName = DefaultEnvironmentName)
        {
            if (_commandLineParser == null)
                _commandLineParser = new CommandLineParser(args);

            _currentEnvironment = _commandLineParser.GetCommandLineVariable(environmentName);

            return _currentEnvironment;
        }

        public static string GetEnvironmentVariable(string environmentName = DefaultEnvironmentName)
        {
            _currentEnvironment = Environment.GetEnvironmentVariable(environmentName);

            return _currentEnvironment;
        }

        public static bool IsDevelopment()
        {
            return IsEnvironment(EnvironmentName.Development, _currentEnvironment);
        }

        public static bool IsQa()
        {

            return IsEnvironment(EnvironmentName.Qa, _currentEnvironment);
        }

        public static bool IsProduction()
        {

            return IsEnvironment(EnvironmentName.Production, _currentEnvironment);
        }

        public static bool IsEnvironment(string hostingEnvironmentName, string environmentName)
        {
            return string.Equals(hostingEnvironmentName, environmentName, StringComparison.OrdinalIgnoreCase);
        }
    }
}
